// src/middleware/error.handler.ts
import { Request, Response, NextFunction } from "express";
import { AppError } from "../utils/errors";
import { fail } from "../utils/response";

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.error(err);
  if (err instanceof AppError) {
    // 已知业务错误：调用 fail 返回统一格式
    return fail(res, err.code, err.message, err.data);
  }
  console.log("has not known error, ", err.message);
  // 未知错误
  return fail(res, 500, "Internal Server Error");
};
